package com.server.controller;

import com.common.context.BaseContext;
import com.common.result.Result;
import com.common.utils.Essay;
import com.common.utils.SpiderUtil;
import com.pojo.dto.CollectionDTO;
import com.pojo.entity.Collection;
import com.server.service.CollectionService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/link")
@Api(tags = "收藏链接")
@Slf4j
public class CollectionController {
    @Autowired
    CollectionService collectionService;

    /*
    * 添加链接，删除链接，查找链接
    * */

    /*
    * 获取搜索关联词
    * */
    @GetMapping("/associated")
    public Result<List<String>> getAssociatedWord(String word){
        List<String> associateWord = SpiderUtil.getAssociateWord(word);
        log.info("搜索词:{}",word);
        log.info("关联词:{}",associateWord);
        return Result.success(associateWord);
    }
    /*
    *根据链接返回文章html内容
    *  */
    @GetMapping("/content")
    public Result getContent(String link){
        String subLink = link.substring(0,link.indexOf('?'));
        log.info("链接:{}",subLink);
        String essayContent = SpiderUtil.getEssayContent(subLink);
        return Result.success(new Object(){
            public String content = essayContent;
        });
    }

    /*
    * 根据搜索词返回文章列表
    * */
    @GetMapping("/essays")
    public Result getEssays(String word){
        List<Essay> essays = SpiderUtil.getEssays(word);
        return Result.success(essays);
    }
    /*
    * 存入链接
    * */
    @PostMapping
    public Result addLink(@RequestBody CollectionDTO collectionDTO){
        Collection collection = new Collection();
        BeanUtils.copyProperties(collectionDTO,collection);
        collection.setUserId(BaseContext.getCurrentId());
        log.info("链接:{}",collection);
        collectionService.insertCollection(collection);
        return Result.success();
    }
    @GetMapping
    public Result<List<Collection>> getLinks(){
        Integer userId = BaseContext.getCurrentId();

        return Result.success(collectionService.selectCollectionByUserId(userId));
    }

    @DeleteMapping
    public Result delLink(@RequestParam("id") Integer id){
        collectionService.deleteCollection(id);
        return Result.success();
    }

    @GetMapping("/title")
    public Result<List<Collection>> getLinksByTitle(@RequestParam("title") String title){
        Integer userId = BaseContext.getCurrentId();
        List<Collection> collections = collectionService.selectCollectionByTitle(title, userId);
        return Result.success(collections);
    }

}
